package com.sunday.common.mq.kafka.study.spring.e21_Brave_Trace_Pull;

import com.sunday.common.mq.kafka.brave.core.TracingKafkaConsumerFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.common.TopicPartition;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.kafka.support.TopicPartitionOffset;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * {@link org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration}
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class MQApi implements InitializingBean {

    @Autowired
    public KafkaTemplate<Object, Object> kafkaTemplate;

    @Autowired
    public TracingKafkaConsumerFactory<Object, Object> kafkaConsumerFactory;

    @Autowired
    public MQController mqController;

    private Consumer<Object, Object> consumer;

    @Override
    public void afterPropertiesSet() {
        consumer = kafkaConsumerFactory.createConsumer();
        consumer.subscribe(List.of("topic15"));
    }

    @GetMapping("/send/{topic}/{key}")
    public void send(@PathVariable String topic, @PathVariable String key) throws InterruptedException, ExecutionException {
        CompletableFuture<SendResult<Object, Object>> future;
        future = kafkaTemplate.send(topic, key, key);
        log.info("[get] {}", future.get());
    }

    @GetMapping("/seek")
    public void seek() {
        Consumer<Object, Object> consumer = kafkaConsumerFactory.createConsumer();
        TopicPartition topicPartition = new TopicPartition("topic15", 0);
        // 该行代码将消费者分配到指定的分区。这意味着消费者将开始从特定分区拉取消息，而不是使用订阅模式
        consumer.assign(Collections.singletonList(topicPartition));
        // 该行代码将消费者的偏移量设置为指定值（在这里是80）。这意味着消费者将从该分区的偏移量为80的位置开始拉取消息
        consumer.seek(topicPartition, 80);
        ConsumerRecords<Object, Object> consumerRecords = consumer.poll(Duration.ofMillis(100));
        consumerRecords.forEach(record -> receive(record));
    }

    @GetMapping("/poll")
    public void poll() {
        ConsumerRecords<Object, Object> consumerRecords;
        // consumer.poll(Duration.ofMillis(100))后会等待最多100毫秒来获取消息
        while (!(consumerRecords = consumer.poll(Duration.ofMillis(100))).isEmpty()) {
            log.info("{}", consumerRecords.count());
            consumerRecords.forEach(record -> receive(record));
        }

    }

    @GetMapping("/pull")
    public void pull() {
        log.info("================================================");
        ConsumerRecord<Object, Object> consumerRecord = kafkaTemplate.receive("topic15", 0, 0L, Duration.ofSeconds(1));
        receive(consumerRecord);
    }

    @GetMapping("/pull1")
    public void pull1() {
        log.info("================================================");
        ConsumerRecord<Object, Object> consumerRecord = kafkaTemplate.receive("topic15", 0, 50L, Duration.ofSeconds(2));
        receive(consumerRecord);
    }

    @GetMapping("/pull2")
    public void pull2() {
        log.info("================================================");
        Collection<TopicPartitionOffset> requested = Arrays.asList(new TopicPartitionOffset("topic15", 0, 0L), new TopicPartitionOffset("topic15", 1, 0L), new TopicPartitionOffset("topic15", 2, 0L));
        ConsumerRecords<Object, Object> consumerRecords = kafkaTemplate.receive(requested);
        consumerRecords.forEach(record -> receive(record));
    }

    public void receive(ConsumerRecord<Object, Object> consumerRecord) {
        mqController.receive(consumerRecord);
        mqController.receive();
    }

}
